<template>
    <el-dialog :model-value="show" title="上传发票" width="60%" align-center
               :before-close="shut" destroy-on-close append-to-body>
        <el-form label-width="100px" status-icon label-position="left"
                 ref="ReceiptRef" :model="receipt" :rules="rules">
            <el-form-item prop="no" label="发票号码">
                <el-input style="width: 100%" placeholder="请输入发票号码" clearable
                          v-model.trim="receipt.no"/>
            </el-form-item>
            <el-form-item prop="totalPrice" label="发票总价">
                <el-input-number style="width: 100%" placeholder="请输入发票总价" clearable
                                 v-model="receipt.totalPrice" @update:model-value="receipt.reimburse = $event"/>
            </el-form-item>
            <el-form-item prop="reimburse" label="报销额度">
                <el-input-number style="width: 100%" clearable disabled
                                 :model-value="receipt.reimburse"/>
            </el-form-item>
            <el-form-item prop="img" label="发票">
                <el-upload
                    ref="UploadRef"
                    :accept="receiptTypes" drag
                    :auto-upload="false"
                    :file-list="receiptFileList"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="handleChange"
                >
                    <el-icon class="el-icon--upload">
                        <UploadFilled/>
                    </el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传pdf文件或jpg,jpeg,png图片,大小不超过5M。
                        </div>
                    </template>
                    <template #file>
                        <div style="position: relative;">
                            <el-button style="z-index:9999999;position:absolute;top: 0;right: 0" link @click="handleRemove"><el-icon :size="20"><close/></el-icon></el-button>
                            <vue-office-pdf v-if="showPdf" :src="previewURL" @rendered="handleRenderedPdf"/>
                            <el-image v-else :src="previewURL"/>
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitForm(ReceiptRef)">完成</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="danger" @click="$emit('update:show',false)">关闭</el-button>
            </span>
        </template>
    </el-dialog>
<!--    <el-image-viewer v-if="showImage" hide-on-click-modal :url-list="[previewURL]"-->
<!--                     @close="showImage = false"/>-->
<!--    <el-dialog v-model="showPdf" title="预览" width="100%">-->
<!--        <vue-office-pdf v-if="showPdf" :src="previewURL"/>-->
<!--    </el-dialog>-->
</template>

<script setup>
import {ref} from 'vue'

import {Close, UploadFilled} from "@element-plus/icons-vue";
import VueOfficePdf from "@vue-office/pdf";

import {createReceiptApi} from "@/apis/receiptManage";
import {getReceiptUploadPresigned, uploadByPresignedUrl} from "@/apis/file";

const props = defineProps(["id", "show"])
const emits = defineEmits(["update:show", "reload"])

const ReceiptRef = ref(null)
const UploadRef = ref(null)
const receipt = ref({})
//判断上传格式
const receiptTypes = "application/pdf,image/jpg,image/png,image/jpeg"
//发票文件列表
const receiptFileList = ref([])
const rules = {
    no: [{required: true, message: '发票号码不能为空!', trigger: ['blur', 'change']}],
    totalPrice: [
        {required: true, message: '发票总价不能为空!', trigger: ['blur', 'change']},
        {
            required: true,
            validator: (rule, value) => value > 0,
            message: "发票总价必须为正数",
            trigger: ['blur', 'change']
        }
    ],
    reimburse: [
        {required: true, message: '报销额度不能为空!', trigger: ['blur', 'change']},
        {
            required: true,
            validator: (rule, value) => value > 0,
            message: "报销额度必须为正数",
            trigger: ['blur', 'change']
        }
    ],
    img: [{
        required: true, message: '发票不能为空!', trigger: ['blur', 'change'],
    }]
}
const handleRenderedPdf = () => {
    document.querySelectorAll('.vue-office-pdf').forEach(value => value.style.overflow = "visible")
    const pdfDom = document.querySelectorAll('.vue-office-pdf-wrapper')
    pdfDom.forEach(value => {
        value.style.background = "#fff"
        value.style.padding = "30px 0"
    })
}
//预览框
let showPdf = ref(false)
let previewURL = ref("")
//上传前判断
const handleChange = (file, fileList) => {
    //判断上传格式
    const typeArr = receiptTypes.split(",")
    let flag = false
    for (const type of typeArr) {
        if (file.raw.type.includes(type)) {
            flag = true
            break
        }
    }
    if (!flag) {
        ElMessage.error("很抱歉您上传的格式不合法")
        fileList.pop()
        return
    }
    if (file.raw.size / 1024 / 1024 > 5) {
        ElMessage.error("您上传的图片大小超过了5MB")
        fileList.pop()
        return;
    }
    receiptFileList.value = [file]
    receipt.value.img = file.raw
    ReceiptRef.value.validateField("img")
    previewURL.value = URL.createObjectURL(file.raw);
    showPdf.value = !!file.raw.type.includes("pdf");
}
const handleExceed = files => {
    UploadRef.value.clearFiles()
    UploadRef.value.handleStart(files[0])
}
const handleRemove = () => {
    UploadRef.value.clearFiles()
    receipt.value.img = ""
    ReceiptRef.value.validateField("img")
}
const resetForm = () => {
    ReceiptRef.value.resetFields()
    receiptFileList.value = []
}
const submitForm = formEl => {
    if (!formEl) return
    formEl.validate(async valid => {
        if (valid) {
            receiptFileList.value[0].status = "uploading"
            const url =  await getReceiptUploadPresigned(receipt.value.img.name);
            let timer = setInterval(()=>{
                receiptFileList.value[0].percentage++
                if(receiptFileList.value[0].percentage === 99) clearInterval(timer)
            },10)
            await uploadByPresignedUrl(url.data, receipt.value.img)
            await createReceiptApi(props.id, {
                ...receipt.value,
                img: url.data.slice(0, url.data.lastIndexOf('?'))
            })
            clearInterval(timer)
            receiptFileList.value[0].percentage = 100
            receiptFileList.value[0].status = "success"
            emits("reload")
            resetForm()
            ElMessage.success("发票上传成功")
            emits("update:show", false)
        }
    })
}

const shut = () => {
    ElMessageBox.confirm(
        '确定关闭吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        resetForm()
        emits("update:show", false)
    }).catch()
}


</script>

<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}

.el-form-item {
    margin-bottom: 20px;
}
:deep(.el-upload-list__item-name):hover{
    cursor: pointer;
}
</style>